<?php
class Component_Appstore_Helpers_Pgateway_Authorizenet extends Component_Appstore_Helpers_Pgateway_Common
{
	const CGI_URL = 'https://secure.authorize.net/gateway/transact.dll';
	const PAYMENT_SUCCESS_URL = '/payment-success';
	const PAYMENT_FAILED_URL = '/payment-failed';
	const VERSION = '3.1';
	const DELIM_DATA = 'TRUE';
	const DELIM_CHAR = "|";
	const RELAY_RESPONSE = "FALSE";
	const METHOD = 'cc';
	const STATUS_NAME = 'CreditCard';

	public function place()
	{
		$this->AssignPost()
			 ->Execute();
	}

	public function getStatusName()
	{
		return self::STATUS_NAME;
	}

	private function Assignpost()
	{
		$paymentData = $this->getPaymentData();
		$paymentData['CardNo'] = isset($paymentData['CardNo']) ? $paymentData['CardNo'] : "";
		$month = $paymentData['expire_date']['month'];
		$year = (strlen($paymentData['expire_date']['year'])==4) ? substr($paymentData['expire_date']['year'],2,2) : $paymentData['expire_date']['year'];

		$authorizenet_mode = App::Helper('Config')->siteInfo('authorizenet_mode');

		$this->setXLogin(App::Helper('Config')->siteInfo('authorizenet_login'))
			 ->setXTranKey(App::Helper('Config')->siteInfo('authorizenet_tran_key'))
			 ->setXVersion(self::VERSION)
			 ->setXDelimData(self::DELIM_DATA)
			 ->setXDelimChar(self::DELIM_CHAR)
			 ->setXRelayResponse(self::RELAY_RESPONSE)
			 ->setXType(App::Helper('Config')->siteInfo('authorizenet_tran_type'))
			 ->setXMethod(self::METHOD);

			if(strtoupper(App::Helper('Config')->siteInfo('authorizenet_mode')) == "TEST"){
				$this->setXTestRequest('TRUE');
			}
			else{
				$this->setXTestRequest('FALSE');
			}

			$CardType = (isset($paymentData['CardType']) ? $paymentData['CardType'] : 'visa');
			if(App::Helper('Validation')->cc($paymentData['CardNo'],Array('type'=>$CardType))){
				$this->setXCardNum($paymentData['CardNo']);
			}
			else{
				throw new AppException($this->__('Invalid credit card information'));
			}

			$this->setXExpDate("{$month}{$year}");

			if($this->getAmount()>0){
				$this->setXAmount($this->getAmount());
			}
			else
			{
				throw new AppException($this->__('Invalid amount changed'));
			}

			$this->setXDescription($this->__("Sample Transaction"));

			$customer  = $this->getBillingAddress();

			$this->setXFirstName((isset($customer['fname'])?$customer['fname']:""))
			     ->setXLastName((isset($customer['lname'])?$customer['lname']:""))
			     ->setXAddress((isset($customer['address_line_1'])?$customer['address_line_1']:""))
			     ->setXState((isset($customer['state'])?$customer['state']:""))
			     ->setXZip((isset($customer['zipcode'])?$customer['zipcode']:""));

		return $this;
	}

	public function Execute()
	{

		$post_values = array(
			"x_login"		=> $this->getXLogin(),
			"x_tran_key"		=> $this->getXTranKey(),
			"x_version"		=> $this->getXVersion(),

			"x_test_request"	=> $this->getXTestRequest(),

			"x_delim_data"		=> $this->getXDelimData(),
			"x_delim_char"		=> $this->getXDelimChar(),
			"x_relay_response"	=> $this->getXRelayResponse(),

			"x_type"		=> $this->getXType(),
			"x_method"		=> $this->getXMethod(),
			"x_card_num"		=> $this->getXCardNum(),
			"x_exp_date"		=> $this->getXExpDate(),

			"x_amount"		=> $this->getXAmount(),
			"x_description"		=> $this->getXDescription(),

			"x_first_name"		=> $this->getXFirstName(),
			"x_last_name"		=> $this->getXLastName(),
			"x_address"		=> $this->getXAddress(),
			"x_state"		=> $this->getXState(),
			"x_zip"			=> $this->getXZip()
		);

		$post_string = "";
		foreach( $post_values as $key => $value ){ $post_string .= "$key=" . urlencode( $value ) . "&"; }
		$post_string = rtrim( $post_string, "& " );

		$cgi_url = App::Helper('Config')->siteInfo('authorizenet_cgi_url');
		$cgi_url = ($cgi_url!="")? $cgi_url :  self::CGI_URL;

		$request = curl_init($cgi_url); // initiate curl object
		curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
		curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
		curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
		curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
		$post_response = curl_exec($request); // execute curl post and store results in $post_response
		curl_close ($request);

		$response_array = explode($post_values["x_delim_char"],$post_response);
		$response_array[0] = isset($response_array[0]) ? $response_array[0] : "";
		if($response_array[0]!=1)
		{
			$response_array[3] = isset($response_array[3]) ? $response_array[3] : $this->__("Network is busy! Please try later") ;
			throw new AppException($this->__($response_array[3]));
		}
	}

    public function htmlToRender()
    {
        $cardTypes = array('visa'=>'Visa',"amex"=>"Amex","bankcard"=>"Bankcard","diners"=>"Diners","disc"=>"Disc","electron"=>"Electron","enroute"=>"Enroute","jcb"=>"JCB","maestro"=>"Maestro","mc"=>"Master Card","solo"=>"Solo","switch"=>"Switch","voyager"=>"Voyager");
        return App::Module("DataGrid")->clear()
                                       ->setDisplay('FormListing')
                                       ->addRow("Card No.",App::Helper('Html')->inputTag("data[Payment][authorizenet][CardNo]","Type Credit Card Numper",array("class"=>"input-small check_notdefault")))
                                       ->addRow("Card Type.",App::Helper('Html')->selectTag("data[Payment][authorizenet][CardType]",$cardTypes,"visa",array("class"=>"check_notempty")))
                                       ->addRow("Exp Date",App::Helper('Html')->ccExpireDate("data[Payment][authorizenet][expire_date]","",array("id"=>"expire_date")))
                                       ->addRow("CVV",App::Helper('Html')->inputTag("data[Payment][authorizenet][cvv]","Type Card Varification Number",array("class"=>"input-small check_notdefault")),"(Last 3 Digits on the back)")
                                       ->Render(true);

    }
}